# encoding:utf-8
"""
删除没在数据库中记录的插件包
"""
import os
import sys
import requests
import json
import shutil


class DelUnuse:

    _del_list = []

    @classmethod
    def execute(cls, host, deltype="local", tarpath=os.getcwd()):
        try:
            ret = requests.get(
                "http://{base}/api/devcli/get_pageinfo".format(base=host))
            p_list = json.loads(ret.text)["data"]
        except requests.exceptions.ConnectionError as identifier:
            print("chk update failed!%s", identifier)

        if deltype == "local":
            cls.localdele_fpath(p_list, tarpath)
        else:
            cls.remotedele_fpath(p_list)

    @classmethod
    def localdele_fpath(cls, plist, tpath):
        useful_filelist = dict()
        useful_dirlist = dict()
        for pobj in plist:
            zipf = "%s@%s.zip" % (pobj["name"], pobj["ver"])
            resdir = "%s@%s" % (pobj["name"], pobj["ver"])
            useful_filelist[zipf] = True
            useful_dirlist[resdir] = True

        for filename in os.listdir(tpath):
            fileobj = os.path.join(tpath, filename)
            if os.path.isfile(fileobj) and not useful_filelist.get(filename):
                print("dele the file--%s" % fileobj)
                os.remove(fileobj)
            if os.path.isdir(fileobj) and not useful_dirlist.get(filename):
                print("dele the path--%s" % fileobj)
                shutil.rmtree(fileobj)

    @classmethod
    def remotedele_fpath(cls, plist):
        # pass
        print(plist, "_->>plist")


if __name__ == "__main__":
    DelUnuse.execute("172.16.50.45", "remote")
